package com.ang.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;

public class Test01 {
    public static void main(String[] args) {
        ShareA shareA = new ShareA();
        new Thread(()->{
            IntStream.range(1,11).forEach(i->{
                shareA.test5(i);
            });
        },"A").start();
        new Thread(()->{
            IntStream.range(1,11).forEach(i->{
                shareA.test10(i);
            });
        },"B").start();
        new Thread(()->{
            IntStream.range(1,11).forEach(i->{
                shareA.test15(i);
            });
        },"C").start();
    }
}

class ShareA {
    private Integer state = 1;
    private Lock lock = new ReentrantLock();

    Condition c1 = lock.newCondition();
    Condition c2 = lock.newCondition();
    Condition c3 = lock.newCondition();

    public void test5(int count) {
        lock.lock();
        try {
            while (state != 1) {
                c1.await();
            }
            IntStream.range(1, 6).forEach(i -> {
                System.out.println(Thread.currentThread().getName() + "---" +count + "\t" + i);
            });
            state = 2;
            c2.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void test10(int count) {
        lock.lock();
        try {
            while (state != 2) {
                c2.await();
            }
            IntStream.range(1, 11).forEach(i -> {
                System.out.println(Thread.currentThread().getName() + "---" +count + "\t" + i);
            });
            state = 3;
            c3.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void test15(int count) {
        lock.lock();
        try {
            while (state != 3) {
                c3.await();
            }
            IntStream.range(1, 16).forEach(i -> {
                System.out.println(Thread.currentThread().getName() + "---" +count + "\t" + i);
            });
            state = 1;
            c1.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}
